package com.satis.compose.get.widget

import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import coil.compose.AsyncImage
import coil.decode.GifDecoder
import coil.request.ImageRequest
import coil.transform.Transformation


/**
 * 图片加载工具
 *
 * @param data 图片数据 可以为图片网址、本地地址或资源id
 * @param modifier 修饰符
 * @param contentScale 使用可选的scale参数来确定要使用的纵横比缩放
 */
@Composable
private fun GetImage(
    data: Any?,
    modifier: Modifier = Modifier,
    placeHolder: Int? = null,
    error: Int? = null,
    contentScale: ContentScale = ContentScale.Crop,
    crossFade: Boolean = false,
    contentDescription: String? = null,
    transformation: Transformation? = null
) {
    when (data) {
        is Int, is String -> {
            val builder = ImageRequest.Builder(LocalContext.current).data(data)
            if (data is String && data.endsWith(".gif")) {
                builder.decoderFactory(GifDecoder.Factory())
            }
            if (placeHolder != null) {
                builder.placeholder(placeHolder)
            }
            if (error != null) {
                builder.error(error)
            }
            builder.allowHardware(true)
            builder.crossfade(crossFade)
            transformation?.also { builder.transformations(it) }

            AsyncImage(
                modifier = modifier,
                model = builder.build(),
                contentScale = contentScale,
                contentDescription = contentDescription
            )
        }
        else -> {
            error("GetImage不支持的data类型")
        }
    }

}


@Composable
fun GetImage(
    resId: Int,
    modifier: Modifier = Modifier,
    placeHolder: Int? = null,
    error: Int? = null,
    contentScale: ContentScale = ContentScale.Crop,
    crossFade: Boolean = false,
    contentDescription: String? = null,
    transformation: Transformation? = null
) {
    GetImage(data = resId,
        modifier = modifier,
        placeHolder = placeHolder,
        error = error,
        contentScale = contentScale,
        crossFade = crossFade,
        contentDescription = contentDescription,
        transformation = transformation
    )
}

@Composable
fun GetImage(
    url: String,
    modifier: Modifier = Modifier,
    placeHolder: Int? = null,
    error: Int? = null,
    contentScale: ContentScale = ContentScale.Crop,
    crossFade: Boolean = false,
    contentDescription: String? = null,
    transformation: Transformation? = null
) {
    GetImage(data = url,
        modifier = modifier,
        placeHolder = placeHolder,
        error = error,
        contentScale = contentScale,
        crossFade = crossFade,
        contentDescription = contentDescription,
        transformation = transformation
    )
}